﻿using System;
using System.Collections.Generic;
using System.IO;
using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.Content.Res;
using Android.Graphics;
using Android.Graphics.Drawables;
using Android.OS;
using Android.Support.Design.Widget;
using Android.Support.V4.App;
using Android.Support.V4.Graphics.Drawable;
using Android.Support.V4.View;
using Android.Support.V7.App;
using Android.Util;
using Android.Views;
using Android.Views.InputMethods;
using Android.Widget;
using API;
using mb;
using mb.Droid;
using mb.DroidLib;
using static Android.Views.MotionEvent;

namespace libmp
{
    public class MainView
    {
        ILog logger = App.logger;
        StartActivity activity = StartActivity.This;
        ViewPager pager;
        TabLayout tab;
        LinearLayout rootLayout;
        List<MyFragment> fragments;

        public static void Load()
        {
            var ctx = StartActivity.This;
            ctx.Window.SetStatusBarColor(Util.MainColor);
            ctx.SupportFragmentManager.BeginTransaction()
                .Replace(ctx.ContentViewId, new MainView().CreateFragment())
                .AddToBackStack("MainTab")
                .Commit();

            ctx.MyDispatchTouchEvent = (e) => MyDispatchTouchEvent(e);

            int lastBSC = 0;
            ctx.SupportFragmentManager.BackStackChanged += (s, e) =>
            {
                var bsc = ctx.SupportFragmentManager.BackStackEntryCount;
                if (bsc < lastBSC) //如果是回退到之前的frag，给它一次刷新的机会
                {
                    var frag = ctx.SupportFragmentManager.FindFragmentById(ctx.ContentViewId);
                    var myfrag = frag as MyFragment;
                    App.logger.Log("backstack changed, count", bsc, " top is", frag, myfrag);
                    if (myfrag != null)
                    {
                        myfrag.MyOnReEnter?.Invoke(myfrag);
                    }
                }
                lastBSC = bsc;
            };
        }

        static bool MyDispatchTouchEvent(MotionEvent e)
        {
            var activity = StartActivity.This;
            if (e.Action == MotionEventActions.Down)
            {
                View fv = activity.CurrentFocus;
                // App.logger.Log("last edittext check1", fv, fv is EditText);
                if (fv is EditText)
                {
                    var rect = new Rect();
                    fv.GetGlobalVisibleRect(rect);
                    var inRect = rect.Contains((int) e.RawX, (int) e.RawY);
                    // App.logger.Log("last edittext check2", inRect);
                    if (!inRect)
                    {
                        Util.HideKeyboard(fv);
                    }
                }

            }

            return activity.DispatchTouchEvent(e);
        }

        MyFragment CreateFragment()
        {
            var ctx = StartActivity.This;
            var mfrag = new MyFragment()
            {
                MyOnCreateView = (f, c) => LoadView(),
                    MyOnPause = (f) =>
                    {
                        // logger.Log("mainview pause");
                    },
                    MyOnResume = (f) =>
                    {
                        logger.Log("mainview resume, ctx id", ctx.ContentViewId, StartActivity.This.ContentViewId);
                    }

            };
            return mfrag;
        }

        public View LoadView()
        {
            if (rootLayout != null) return rootLayout;

            var ctx = StartActivity.This;
            var so = mb.ServiceLocator.Instance.Get<IStartOption>();
            var vctest = so.GetBoolValue("vctest");

            rootLayout = new LinearLayout(ctx);
            rootLayout.Orientation = Android.Widget.Orientation.Vertical;
            rootLayout.SetBackgroundColor(Color.Black);
            rootLayout.Focusable = true; //让其它edittext控件可以空闲一下，不要老是闪光标
            rootLayout.FocusableInTouchMode = true;

            fragments = new List<MyFragment>
            {
                Util.FragmentFrom(typeof(HomeView)),
                Util.FragmentFrom(typeof(CategoryView)),
                Util.FragmentFrom(typeof(MemberCenterView)),
                Util.FragmentFrom(typeof(MeView)),
            };
            if (vctest)
            {
                fragments.Add(Util.FragmentFrom(typeof(TestView)));
            }

            pager = new ViewPager(ctx);
            pager.Id = View.GenerateViewId();
            pager.Adapter = new MyPagerAdapter(ctx, ctx.SupportFragmentManager) { fragments = fragments };
            pager.LayoutParameters = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, 0, 1);
            pager.OffscreenPageLimit = 4;
            rootLayout.AddView(pager);

            var sep = new View(ctx);
            sep.LayoutParameters = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, 2);
            sep.SetBackgroundColor(Color.Black);
            rootLayout.AddView(sep);

            var inflater = LayoutInflater.From(ctx);
            var ifview = inflater.Inflate(Resource.Layout.htabs_no_ripple, rootLayout);
            var tabv = rootLayout.FindViewById(Resource.Id.sliding_tabs);
            tab = tabv as TabLayout;
            if (tab == null)
            {
                mb.Droid.Util.ShowMsgBox("资源ID错乱，请重编引擎");
                return rootLayout;
            }
            logger.Log("find tab---", Resource.Id.sliding_tabs, tab);
            tab.SetSelectedTabIndicatorColor(Color.Rgb(133, 55, 88));

            tab.SetupWithViewPager(pager);
            tab.SetSelectedTabIndicatorHeight(0);
            tab.TabRippleColor = new ColorStateList(new int[][] { new int[] { } }, new int[] { Color.Transparent });

            var icons = new string[] { "Home", "Classification", "Receive", "PersonalCenter", "Test" };
            for (int i = 0; i < fragments.Count; i++)
            {
                tab.GetTabAt(i).SetIcon(Util.DrawableFromFile($"{App.HotStorageRoot}/res/maintab/{icons[i]}.png"));
            }

            var colors = new Color[] { Util.MainColor, Color.Rgb(125, 125, 125), };
            tab.TabTextColors = Util.MakeColorStateList(colors[1], colors[0]);

            tab.TabSelected += (s, e) =>
            {
                e.Tab.Icon.SetColorFilter(new Color(colors[0]), PorterDuff.Mode.SrcIn);
            };
            tab.TabUnselected += (s, e) =>
            {
                e.Tab.Icon.SetColorFilter(new Color(colors[1]), PorterDuff.Mode.SrcIn);
            };
            tab.TabReselected += (s, e) =>
            {
                // logger.Log("reselect", e.Tab.Position);
                var frag = (pager.Adapter as MyPagerAdapter).fragments[e.Tab.Position];
                object owner = null;
                frag.dict.TryGetValue("owner", out owner);
                owner?.GetType().GetMethod("ReClick")?.Invoke(owner, null);

            };

            //初始颜色 
            tab.GetTabAt(0).Icon.SetColorFilter(new Color(colors[0]), PorterDuff.Mode.SrcIn);

            #region test open
            var dt = so.GetStringValue("defaulttab");
            if (dt != null)
            {
                int idx;
                if (dt == "movie") { MoviePlayView.OpenPlayView(DataStore.store.video[0]); }
                else if (dt == "offlineCache") { MeView.OfflineCache(); }
                else if (dt == "userRegister") { MeView.Register(); }
                else if (dt == "userLogin") { MeView.LogIn(); }
                else if (int.TryParse(dt, out idx)) { tab.GetTabAt(idx).Select(); }
            }
            #endregion

            return rootLayout;
        }

    }

}